﻿Ext.data.PolymorphicAssociation = Ext.extend(Ext.data.Association, {

    constructor: function (config) {
        Ext.data.PolymorphicAssociation.superclass.constructor.call(this, config);

        var ownerProto = this.ownerModel.prototype, // 主model原型
            name = this.name;

        Ext.applyIf(this, {
            associationIdField: this.ownerName.toLowerCase() + "_id"
        });

        ownerProto[name] = this.createStore();
    },


    createStore: function () {
        var association = this,
            ownerName = this.ownerName, // 主model名
            storeName = this.name + "Store", // 从store名称
            associatedModel = this.associatedModel, //从model
            primaryKey = this.primaryKey, // 主键
            associationIdField = 'associated_id', 
            associationModelField = 'associated_model';

        return function () {
            var me = this,
                modelDefaults = {},
                config, filters;

            // 如果主model实例没有指定store
            if (me[storeName] == undefined) {
                // 筛选从模型的记录
                filters = [
                    {
                        property: associationIdField,
                        value: me.get(primaryKey), // （从主模型的角度读取）
                        exactMatch: true
                    },
                    {
                        property: associationModelField,
                        value: ownerName, // 主model名
                        exactMatch: true
                    }
                ];

                modelDefaults[associationIdField] = me.get(primaryKey);
                modelDefaults[associationModelField] = ownerName;

                config = Ext.apply({}, association.storeConfig || {}, {
                    model: associatedModel, // 从model
                    filters: filters,
                    remoteFilter: false,
                    modelDefaults: modelDefaults // 创建model实例时所用的默认配置
                });

                me[storeName] = new Ext.data.Store(config);
            }

            return me[storeName];
        };
    }
});